<?php

/**
 * Description of DashboardController
 *
 * @author drackor
 */
class Driver_DashboardController extends Model3_Controller
{

    public function init()
    {
        if (!Model3_Auth::isAuth())
        {
            $this->redirect('Index/index');
        }
    }

    /**
     * Próximas rutas del driver
     */
    public function schedulesAction()
    {
        $userId = Model3_Auth::getCredentials('id');
        $em = $this->getEntityManager('DefaultDb');
        $scheduleAdapter = $em->getRepository('DefaultDb_Entities_Schedule');
        $scheduleId = null;

        $schedules = $scheduleAdapter->getSchedulesByUserAndDate($userId);
        date_default_timezone_set('America/Mexico_City'); //Asignas la zona horaria de tu país.
        setlocale(LC_TIME, 'spanish'); //Fijamos el tiempo local
        foreach ($schedules as $key => $schedule)
        {
            $time = new DateTime($schedule['startDateTimeRoute']);
            $schedules[$key]['route_date_format'] = strftime("%A, %d %B %Y, %H:%M hrs", $time->getTimestamp());
        }
        if (count($schedules) > 0)
        {
            $scheduleId = $schedules[0]['schedule_id'];
        }
        $schedules = array_merge($schedules, $schedules, $schedules, $schedules);
        $this->view->schedules = $schedules;
        $this->view->getJsManager()->addJsVarEncode('urlDetailRoute', $this->view->url(array(
                    'controller' => 'Dashboard',
                    'action' => 'detailRoute',
                    'id' => $scheduleId)));
        $this->view->setTemplate('Responsive');
    }

    /**
     * AJAX
     * Se invoca para obtener los detalles de una ruta
     */
    public function detailRouteAction()
    {
        $em = $this->getEntityManager('DefaultDb');
        $scheduleAdapter = $em->getRepository('DefaultDb_Entities_Schedule');

        $scheduleId = $this->getRequest()->getParam('id');
        if ($scheduleId !== null)
        {
            $points = $scheduleAdapter->getPointsById($scheduleId);
            $schedule = $scheduleAdapter->getScheduleById($scheduleId);
            date_default_timezone_set('America/Mexico_City'); //Asignas la zona horaria de tu país.
            setlocale(LC_TIME, 'spanish'); //Fijamos el tiempo local
            foreach ($points as $key => $point)
            {
                $time = new DateTime($point['route_date'], new DateTimeZone('America/Mexico_City'));
                $points[$key]['route_time'] = $time->format('H:i');
                $points[$key]['route_date_format'] = strftime("%A, %d %B %Y, %H:%M hrs", $time->getTimestamp());
            }
            $this->view->points = $points;
            $this->view->schedule = $schedule[0];
        }
        $this->view->setUseTemplate(false);
    }

    public function routeAction()
    {
        $em = $this->getEntityManager('DefaultDb');
        $routeAdapter = $em->getRepository('DefaultDb_Entities_Route');
        $scheduleAdapter = $em->getRepository('DefaultDb_Entities_Schedule');

        $params = $this->getRequest()->getPost();
        $success = false;
        if (count($params) > 0)
        {
            if (isset($params['routeId']) === true && isset($params['scheduleId']) === true)
            {
                $routeId = $params['routeId'];
                $scheduleId = $params['scheduleId'];
                $route = $routeAdapter->find($routeId);
                $points = $scheduleAdapter->getPointsById($scheduleId);
                $pointsFormat = array(
                );
                $points = array_merge($points, $points, $points);
                $points[0]['shipping_date'] = date('Y-m-d H:i:s');
                $points[1]['shipping_date'] = date('Y-m-d H:i:s');
                $nextPoint = null;
                $checkIn = null; // Indeterminado
                foreach ($points as $key => $point)
                {
                    $strRouteTime = '--:--';
                    try
                    {
                        $routeTime = new DateTime($point['route_date']);
                        $strRouteTime = $routeTime->format('H:i');
                    }
                    catch (Exception $exc)
                    {
                        
                    }
                    $point['route_date_format'] = $strRouteTime;
                    $strShippingTime = '--:--';
                    try
                    {
                        if ($point['shipping_date'] !== null)
                        {
                            $shippingTime = new DateTime($point['shipping_date']);
                            $strShippingTime = $shippingTime->format('H:i');
                        }
                        else
                        {
                            /// Punto aún no visitado
                            if ($checkIn === true)
                            {
                                /// Puntos no visitado, pero que no es el primer
                                /// punto. Es decir aun no se ha visitado, pero
                                /// no es el próximo punto para hacer check-in.
                                $checkIn = false;
                            }
                            if ($checkIn === null)
                            {
                                /// Estamos en un punto no visitado, y como es
                                /// indeterminado (null) significa que es el 
                                /// primer punto que no se ha visitado, es decir
                                /// el próximo check-in.
                                $checkIn = true; // Primer punto no visitado
                            }
                        }
                    }
                    catch (Exception $exc)
                    {
                        
                    }
                    $routeTime = new DateTime($point['route_date']);
                    $shippingTime = new DateTime($point['shipping_date']);
                    $interval = $routeTime->diff($shippingTime);
                    $point['shipping_date_format'] = $strShippingTime;
                    $point['check_in'] = $checkIn;
                    if ($checkIn === true)
                    {
                        $nextPoint = $point; // Siguiente punto a visitar
                    }
                    $pointsFormat[] = $point;
                }
                $this->view->route = $route;
                $this->view->points = $pointsFormat;
                $this->view->nextPoint = $nextPoint;
            }
            $success = true;
        }
        $this->view->success = $success;
        $this->view->getCssManager()->addCss('clock.css');
        $this->view->getJsManager()->addJs('clock.js');
        $this->view->getJsManager()->addJs('moment.min.js');
        $this->view->setTemplate('Responsive');
    }

    public function pointAction()
    {
        $em = $this->getEntityManager('DefaultDb');
        $saAdapter = $em->getRepository('DefaultDb_Entities_SequentialActivities');
        $success = false;

        //if ($this->getRequest()->isPost() === true)   {
        $params = $this->getRequest()->getPost();
        $params = array();
        $params['sequentialActititieId'] = 123;
        if (isset($params['sequentialActititieId']) === true)
        {
            $sequentialActititieId = (int) $params['sequentialActititieId'];
            $sequentialActititieId = 123;
            $sa = $saAdapter->find($sequentialActititieId);
            if ($sa !== null)
            {
                $packages = $saAdapter->getPackagesBySequentialActivity($sa->getId());
                $rp = $sa->getRoutePoint();
                if ($rp !== null)
                {
                    $point = $rp->getPoint();
                }
                $this->view->packages = $packages;
                $success = true;
            }
        }
        // }
        $this->view->setTemplate('Responsive');
        $this->view->success = true;
        $this->view->getJsManager()->addJsVarEncode('urlSuccess', $this->view->url(array(
                    'controller' => 'Packages', 'action' => 'success')));
        $this->view->getJsManager()->addJsVarEncode('urlWarning', $this->view->url(array(
                    'controller' => 'Packages', 'action' => 'warning')));
        $this->view->getJsManager()->addJsVarEncode('urlDanger', $this->view->url(array(
                    'controller' => 'Packages', 'action' => 'danger')));
    }

    public function indexAction()
    {
        $userId = Model3_Auth::getCredentials('id');
        $em = $this->getEntityManager('DefaultDb');

        $user = $em->find('DefaultDb_Entities_User', $userId);

        $this->view->user = $user;
        $scheduleAdapter = $em->getRepository('DefaultDb_Entities_Schedule');
        $routesAdapter = $em->getRepository('DefaultDb_Entities_Route');
        $ordersAdapter = $em->getRepository('DefaultDb_Entities_M3CommerceOrder');
        $routePointAdapter = $em->getRepository('DefaultDb_Entities_RoutePoint');
        $date = new DateTime();
        if ($this->getRequest()->isPost())
        {
            $post = $this->getRequest()->getPost();
//            var_dump($post);
            //cambiamos el estatus que recibimos de la orden solo cambia de "en centro de intercambio" a "en ruta" o viceversa
            if (is_array($post) && isset($post['toInterchangeCenter']) && isset($post['idOrder']))
            {
                $status = $post['toInterchangeCenter'];
                $idOrder = $post['idOrder'];
                $order = $ordersAdapter->find($idOrder);
//                var_dump($order);
//                var_dump($status);
                if ($order)
                {
                    if ($status == DefaultDb_Entities_M3CommerceOrder::SHIPPING_STATUS_IN_INTERCHANGE_CENTER)
                    {

                        switch ($order->getShippingStatus())
                        {
                            case DefaultDb_Entities_M3CommerceOrder::SHIPPING_STATUS_TO_SHIPPED:
                            case DefaultDb_Entities_M3CommerceOrder::SHIPPING_STATUS_SHIPPED:
                                //var_dump($status);
                                $order->setShippingStatus($status);
                                $em->persist($order);
                                break;
                        }
                    }
                    else if ($status == DefaultDb_Entities_M3CommerceOrder::SHIPPING_STATUS_SHIPPED)
                    {
//                        var_dump($status);
                        switch ($order->getShippingStatus())
                        {
                            case DefaultDb_Entities_M3CommerceOrder::SHIPPING_STATUS_TO_SHIPPED:
                            case DefaultDb_Entities_M3CommerceOrder::SHIPPING_STATUS_IN_INTERCHANGE_CENTER:
                                //var_dump($status);
                                $order->setShippingStatus($status);
                                $em->persist($order);
                                break;
                        }
                    }
                    $em->flush();
                }
            }
        }
        $schedule = $scheduleAdapter->getScheduleByUserAndDate($user, $date);
        $registers = false;
        if ($schedule)
        {
            $startDate = new DateTime($date->format('Y-m-d')); //Esta se debe usar para la fecha actual
            $route = $schedule->getRoute(); //$routesAdapter->find($schedule->getRoute()->getId());
            $hourDate = $schedule->getStartDate();
            $hour = $hourDate->format('H');
            $registers = $routePointAdapter->getSecuencialActivityByDateByRoute($startDate, $route, $schedule->getStartDate()->format('Y-m-d H:i:s'));
            //var_dump($registers);
            //$registers = $ordersAdapter->getSecuencialActivityByDateByRoute($startDate,$route,$schedule->getStartDate()->format('Y-m-d H:i:s'));
        }
        $this->view->registers = $registers;
    }

    public function selectReasonClientAction()
    {
        $this->view->result = false;
        if ($this->getRequest()->isPost())
        {
            $post = $this->getRequest()->getPost();

            if (isset($post['clientCode']))
            {
                $clientCode = $post['clientCode'];
                $em = $this->getEntityManager('DefaultDb');
                //Obtiene el usuario cliente
                $userRepos = $em->getRepository('DefaultDb_Entities_User');
                $user = $userRepos->findOneBy(array(
                    'code' => $clientCode));
                if ($user)
                {
                    $viewUser = new Model3_Session_Namespace('viewUser');
                    $viewUser->id = $user->getId();
                    $this->view->user = $user;
                    $this->view->result = true;
                }
            }
        }
        $this->view->getCssManager()->addCss('view/scripts/Driver/Dashboard/selectReasonClient' . VERSION_CSS . '.css');
    }

    public function redirectRecolectionAction()
    {
        if ($this->getRequest()->isPost())
        {
            $post = $this->getRequest()->getPost();
            if (isset($post['clientCode']))
            {
                $clientCode = $post['clientCode'];
                $em = $this->getEntityManager('DefaultDb');
                $userRepos = $em->getRepository('DefaultDb_Entities_User');
                $user = $userRepos->findOneBy(array(
                    'code' => $clientCode));
                if ($user)
                {
                    $viewUser = new Model3_Session_Namespace('viewUser');
                    $viewUser->id = $user->getId();
                    $this->redirect('User/BackStore/orders');
                }
            }
        }
        $this->redirect('Driver/Dashboard/index');
    }

    public function redirectShippingAction()
    {
        if ($this->getRequest()->isPost())
        {
            $post = $this->getRequest()->getPost();
            if (isset($post['clientCode']))
            {
                $clientCode = $post['clientCode'];
                $em = $this->getEntityManager('DefaultDb');
                $userRepos = $em->getRepository('DefaultDb_Entities_User');
                $user = $userRepos->findOneBy(array(
                    'code' => $clientCode));
                if ($user)
                {
                    $viewUser = new Model3_Session_Namespace('viewUser');
                    $viewUser->id = $user->getId();
                    $this->redirect('User/BackStore/shopping');
                }
            }
        }
        $this->redirect('Driver/Dashboard/index');
    }

    public function redirectVisitAction()
    {
        if ($this->getRequest()->isPost())
        {
            $post = $this->getRequest()->getPost();
            if (isset($post['clientCode']))
            {
                $clientCode = $post['clientCode'];
                $em = $this->getEntityManager('DefaultDb');
                $userRepos = $em->getRepository('DefaultDb_Entities_User');
                $user = $userRepos->findOneBy(array(
                    'code' => $clientCode));
                if ($user)
                {
                    $viewUser = new Model3_Session_Namespace('viewUser');
                    $viewUser->id = $user->getId();
                    $this->redirect('Driver/FavoriteUsers/index');
                }
            }
        }
        $this->redirect('Driver/Dashboard/index');
    }

    public function changeStatusToInterchangeCenterAction()
    {
        if ($this->getRequest()->isPost())
        {
            $post = $this->getRequest()->getPost();
            if (is_array($post) && in_array('toInterchangeCenter'))
            {
                $status = $post['toInterchangeCenter'];
                $em = $this->getEntityManager('DefaultDb');
                $userRepos = $em->getRepository('DefaultDb_Entities_User');
                $user = $userRepos->findOneBy(array(
                    'code' => $clientCode));
                if ($user)
                {
                    $viewUser = new Model3_Session_Namespace('viewUser');
                    $viewUser->id = $user->getId();
                }
            }
        }
        $this->redirect('Driver/Dashboard/index');
    }

    /* @todo: meter cuando se agrega la orden a centro de intercambio y cuando se recolecta de centro de intercambio */
}